package com.atguigu.exam.service.impl;

import com.atguigu.exam.entity.*;
import com.atguigu.exam.mapper.ExamRecordMapper;
import com.atguigu.exam.mapper.QuestionMapper;
import com.atguigu.exam.service.*;
import com.atguigu.exam.vo.SubmitAnswerVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 考试服务实现类
 */
@Service
@Slf4j
public class ExamServiceImpl extends ServiceImpl<ExamRecordMapper, ExamRecord> implements ExamService {

    @Autowired
    private AnswerRecordService answerRecordService;
    @Autowired
    private PaperService paperService;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private AIService aiService;

    /**
     * 提交答案 - 学生提交考试答案
     * @param examRecordId 考试记录ID
     * @param answers      答案列表
     */
    @Transactional
    @Override
    public boolean submitAnswers(Integer examRecordId, List<SubmitAnswerVo> answers) {
        //根据考试记录ID查询开始详情记录
        ExamRecord examRecord = baseMapper.selectById(examRecordId);
        //设置考试状态为已完成
        examRecord.setStatus("已完成");
        //设置考试结束时间
        examRecord.setEndTime(LocalDateTime.now());
        //更新考试记录
        baseMapper.updateById(examRecord);
        //将List<SubmitAnswerVo> answers转换为List<AnswerRecord>类型
        List<AnswerRecord> answerRecordList = answers.stream().map(
                answer -> {
                    AnswerRecord answerRecord = new AnswerRecord(examRecordId, answer.getQuestionId(), answer.getUserAnswer());
                    return answerRecord;
                }
        ).collect(Collectors.toList());
        //调用方法批量插入 answerRecordList考试记录
        answerRecordService.saveBatch(answerRecordList);

        //调用判卷方法
        gradePaper(examRecordId);

        throw new RuntimeException("考试结束");
    }

    /**
     * 判卷 - 批阅试卷
     * @param examRecordId 考试记录ID
     */
    private void gradePaper(Integer examRecordId) {
        //根据id查询考试记录详情
        ExamRecord examRecord = getExamRecordById(examRecordId);
        //获取答案记录列表
        List<AnswerRecord> answerRecords = examRecord.getAnswerRecords();
        //获取试卷中所有的问题列表
        List<Question> questions = examRecord.getPaper().getQuestions();
        // 创建一个Map，将题目ID映射为题目对象
        Map<Long, Question> questionMap = questions.stream().collect(Collectors.toMap(
                Question::getId,
                question -> question
        ));
        //遍历答案记录列表
        answerRecords.forEach(answerRecord -> {
            //获取答案记录中的问题id
            Integer questionId = answerRecord.getQuestionId();
            //根据id获取问题
            Question question = questionMap.get(questionId);
            //判断题型是否是判断题  将用户提交的T->True F->False
            if ("JUDGE".equalsIgnoreCase(question.getType())) {
                //将判断题的答案进行转换成数据库可读取的格式
                answerRecord.setUserAnswer(
                        answerRecord.getUserAnswer().equalsIgnoreCase("T") ? "TRUE" : "FALSE"
                );
            }
            //获取问题的正确答案
            String correctAnswer = question.getAnswer().getAnswer();
            //获取用户提交的答案
            String userAnswer = answerRecord.getUserAnswer();
            //判断是不是非简答题
            if (!"TEXT".equalsIgnoreCase(question.getType())){
                //判断用户提交的答案是不是一致的      系统答案必须在前面,防止用户没有答题报null异常
                if (correctAnswer.equalsIgnoreCase(userAnswer)){
                    //答案一直,用户试卷题目得分
                    //设置分数
                    answerRecord.setScore(question.getPaperScore().intValue());
                    //设置题目答题状态为正确
                    answerRecord.setIsCorrect(1);
                }else{
                    //用户答题错误或没有答题
                    //设置0分
                    answerRecord.setScore(0);
                    //设置题目答题状态为错误
                    answerRecord.setIsCorrect(0);
                }
            }
            //调用Ai处理简答题
            GradingResult gradingResult =  aiService.gradeTextQuestion(question,userAnswer);


        });
    }

    /**
     * 根据ID获取考试记录详情 - 查询具体考试结果
     */
    @Override
    public ExamRecord getExamRecordById(Integer id) {
        //根据id查询考试详情
        ExamRecord examRecord = baseMapper.selectById(id);

        //获取试卷的题目列表
        Paper paper = paperService.getDetailById(examRecord.getExamId());
        //试卷中没有选项跟答案需要获取
        //获取试卷的题目列表
        List<Question> questions = paper.getQuestions();
        questions.forEach(
                question -> {
                    //根据题目id获取题目的选项
                    Question questionById = questionMapper.getQuestionById(question.getId());
                    //设置题目选项
                    question.setChoices(questionById.getChoices());
                    //设置题目答案
                    question.setAnswer(questionById.getAnswer());
                }
        );
        //对题目进行排序
        questions.sort(((o1, o2) -> o1.getType().compareTo(o2.getType())));

        examRecord.setPaper(paper);

        return examRecord;
    }

    /**
     * 标准化判断题答案，将T/F转换为TRUE/FALSE
     * @param answer 原始答案
     * @return 标准化后的答案
     */
    private String normalizeJudgeAnswer(String answer) {
        if (answer == null || answer.trim().isEmpty()) {
            return "";
        }

        String normalized = answer.trim().toUpperCase();
        switch (normalized) {
            case "T":
            case "TRUE":
            case "正确":
                return "TRUE";
            case "F":
            case "FALSE":
            case "错":
                return "FALSE";
            default:
                return normalized;
        }
    }

}